<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Storage;

class FileController extends Controller
{
    public function upload(Request $request)
    {
        if (!$request->hasFile('file')) {
            return response()->json(['code' => 500,'msg' =>'上传文件不能为空']);
        }
        $file = $request->file('file');
        if (!starts_with($file->getMimeType(), 'image')) {
            return response()->json(['code' => 501,'msg' =>'上传文件类型错误']);
        }
        if (!$file->isValid()) {
            return response()->json(['code' => 502,'msg' =>'上传文件出错']);
        }
        $newFileName = md5(time() . rand(0, 10000)) . '.' . $file->getClientOriginalExtension();
        $savePath = date('Ym', time()) . '/' . $newFileName;
        $bytes = Storage::put(
            $savePath,
            file_get_contents($file->getRealPath())
        );
        if (!Storage::exists($savePath)) {
            return response()->json(['code' => 504,'msg' =>'保存文件出错']);
        }
        return response()->json(['code' => 200,'msg' => '上传成功','path' => $savePath]);
    }
}
